package com.lh.learning.mq.rabbitmq;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import java.util.concurrent.atomic.AtomicInteger;

@RocketMQTransactionListener
public class RocketTranscationListener implements RocketMQLocalTransactionListener {

    private AtomicInteger count = new AtomicInteger(0);

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        int num = count.incrementAndGet();
        System.out.println("num:" + num);
        if (num % 3 == 0) {
            return RocketMQLocalTransactionState.COMMIT;
        }
        if (num % 2 == 0) {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        int num = count.get();
        System.out.println("check num:" + num);
        if (num % 2 == 0) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
